<template>
  <div class="custom-modal-mask" v-if="visible">
    <div class="custom-modal" style="max-width:700px;">
      <div class="custom-modal-header">
        <h3 class="custom-modal-title">{{ isEdit ? '编辑知识' : '添加知识' }}</h3>
        <button class="custom-modal-close" @click="onClose">&times;</button>
      </div>
      <div class="custom-modal-body">
        <div class="form-group">
          <label class="form-label">知识标题</label>
          <input type="text" class="form-input" v-model="form.title" placeholder="请输入知识标题" />
        </div>
        <div class="form-group">
          <label class="form-label">分类</label>
          <select class="form-select" v-model="form.categoryId">
            <option v-for="cat in categoryOptions" :key="cat.id" :value="cat.id">{{ cat.name }}</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">知识内容</label>
          <QuillEditor v-model:content="form.content" contentType="html" style="height: 200px;" />
        </div>
        <div class="form-group">
          <label class="form-label">标签</label>
          <input type="text" class="form-input" v-model="tagsInput" placeholder="请输入标签，用逗号分隔" @blur="onTagsBlur" />
          <div class="custom-tags">
            <span class="custom-tag" v-for="tag in form.tags" :key="tag">
              {{ tag }}
              <span class="custom-tag-close" @click="removeTag(tag)">&times;</span>
            </span>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">关键词</label>
          <input type="text" class="form-input" v-model="keywordsInput" placeholder="请输入关键词，用逗号分隔" @blur="onKeywordsBlur" />
          <div class="custom-tags">
            <span class="custom-tag custom-tag-keyword" v-for="kw in form.keywords" :key="kw">
              {{ kw }}
              <span class="custom-tag-close" @click="removeKeyword(kw)">&times;</span>
            </span>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">发布状态</label>
          <select class="form-select" v-model="form.status">
            <option value="published">已发布</option>
            <option value="draft">草稿</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">权重（越大越靠前）</label>
          <input type="number" class="form-input" v-model="form.weight" placeholder="请输入权重，默认0" min="0" />
        </div>
      </div>
      <div class="custom-modal-footer">
        <button class="btn btn-secondary" @click="onClose">取消</button>
        <button class="btn btn-primary" @click="onSubmit">保存知识</button>
        <button class="btn btn-info" style="margin-left:10px;" @click="openPreview('pc')">PC预览</button>
        <button class="btn btn-info" style="margin-left:6px;" @click="openPreview('h5')">H5预览</button>
      </div>
    </div>
    <!-- 独立预览弹窗 -->
    <div v-if="showPreviewDialog" class="preview-modal-mask">
      <div class="preview-modal">
        <div class="preview-modal-header">
          <span>{{ previewMode==='pc' ? 'PC端预览' : 'H5预览' }}</span>
          <button class="preview-modal-close" @click="closePreview">&times;</button>
        </div>
        <div class="preview-modal-body">
          <div v-if="previewMode==='pc'" class="preview-pc-card">
            <h3>{{ form.title }}</h3>
            <div v-html="form.content"></div>
          </div>
          <div v-else class="h5-preview-wrap">
            <div class="h5-preview-phone">
              <h4>{{ form.title }}</h4>
              <div v-html="form.content" class="h5-preview-content"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, computed, nextTick } from 'vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { ElMessage } from 'element-plus'

const props = defineProps<{ visible: boolean; modelValue?: any; categoryOptions: any[] }>()
const emit = defineEmits(['update:visible', 'save'])

const isEdit = computed(() => !!props.modelValue)
const form = ref({
  title: '',
  categoryId: '',
  content: '',
  tags: [] as string[],
  keywords: [] as string[],
  status: 'published',
  weight: 0,
})
const tagsInput = ref('')
const keywordsInput = ref('')
const previewMode = ref('')
const showPreviewDialog = ref(false)

watch(
  () => props.visible,
  (val) => {
    if (val) {
      if (props.modelValue) {
        form.value = { ...props.modelValue, tags: [...(props.modelValue.tags||[])], keywords: [...(props.modelValue.keywords||[])] }
      } else {
        form.value = { title: '', categoryId: '', content: '', tags: [], keywords: [], status: 'published', weight: 0 }
      }
      tagsInput.value = ''
      keywordsInput.value = ''
      previewMode.value = ''
    }
  },
  { immediate: true }
)

function onTagsBlur() {
  if (tagsInput.value) {
    const arr = tagsInput.value.split(',').map(t => t.trim()).filter(Boolean)
    form.value.tags = Array.from(new Set([...form.value.tags, ...arr]))
    tagsInput.value = ''
  }
}
function removeTag(tag: string) {
  form.value.tags = form.value.tags.filter(t => t !== tag)
}
function onKeywordsBlur() {
  if (keywordsInput.value) {
    const arr = keywordsInput.value.split(',').map(t => t.trim()).filter(Boolean)
    form.value.keywords = Array.from(new Set([...form.value.keywords, ...arr]))
    keywordsInput.value = ''
  }
}
function removeKeyword(kw: string) {
  form.value.keywords = form.value.keywords.filter(t => t !== kw)
}
function openPreview(mode: 'pc'|'h5') {
  previewMode.value = mode
  showPreviewDialog.value = true
}
function closePreview() {
  showPreviewDialog.value = false
}
function onClose() {
  emit('update:visible', false)
}
function isQuillContentEmpty(html: string) {
  if (!html) return true
  // 文案管理中加了<div>包裹
  const div = document.createElement('div')
  div.innerHTML = `<div>${html}</div>`
  const text = div.innerText.replace(/\u200B/g, '').trim()
  return !text
}

function onSubmit() {
  if (!form.value.title) return ElMessage.warning('请填写标题')
  if (!form.value.categoryId) return ElMessage.warning('请选择分类')
  if (isQuillContentEmpty(form.value.content)) return ElMessage.warning('请填写内容')
  // 权重为0允许保存
  emit('save', { ...form.value })
  emit('update:visible', false)
}
</script>

<style scoped>
.custom-modal-mask {
  position: fixed;
  z-index: 2000;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
}
.custom-modal {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.18);
  width: 100%;
  max-width: 700px;
  padding: 0;
  overflow: hidden;
  animation: fadeIn .2s;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px); }
  to { opacity: 1; transform: none; }
}
.custom-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px 0 24px;
}
.custom-modal-title {
  font-size: 20px;
  font-weight: 600;
  color: #222;
}
.custom-modal-close {
  background: none;
  border: none;
  font-size: 28px;
  color: #888;
  cursor: pointer;
  line-height: 1;
}
.custom-modal-body {
  flex: 1 1 auto;
  overflow-y: auto;
  max-height: 60vh;
  min-height: 100px;
  padding: 16px 24px 0 24px;
}
.form-group {
  margin-bottom: 18px;
}
.form-label {
  display: block;
  font-weight: 500;
  margin-bottom: 6px;
  color: #333;
}
.form-input, .form-select {
  width: 100%;
  padding: 10px 14px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 15px;
  outline: none;
  transition: border 0.2s;
}
.form-input:focus, .form-select:focus {
  border-color: #4361ee;
}
.custom-tags {
  margin-top: 6px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}
.custom-tag {
  background: #f0f4ff;
  color: #4361ee;
  border-radius: 8px;
  padding: 2px 10px;
  font-size: 13px;
  display: flex;
  align-items: center;
}
.custom-tag-keyword {
  background: #f7f7fa;
  color: #888;
}
.custom-tag-close {
  margin-left: 4px;
  cursor: pointer;
  color: #aaa;
  font-size: 14px;
}
.custom-modal-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
  padding: 18px 24px 0 24px;
}
.btn {
  padding: 8px 18px;
  border: none;
  border-radius: 6px;
  font-size: 15px;
  cursor: pointer;
  transition: background 0.2s;
}
.btn-primary {
  background: #4361ee;
  color: #fff;
}
.btn-primary:hover {
  background: #3a56d4;
}
.btn-secondary {
  background: #f5f5f5;
  color: #333;
}
.btn-info {
  background: #eaf0ff;
  color: #4361ee;
}
.btn-info:hover {
  background: #dbe6ff;
}
.custom-preview-area {
  padding: 24px 24px 0 24px;
}
.preview-pc-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  padding: 24px;
  min-height: 120px;
}
.h5-preview-wrap {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}
.h5-preview-phone {
  width: 375px;
  height: 667px;
  background: #f5f5f5;
  border: 1px solid #ccc;
  border-radius: 32px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  overflow: auto;
  padding: 24px 12px;
  position: relative;
  margin: 0 auto;
}
.h5-preview-content {
  width: 100%;
  min-height: 100px;
  word-break: break-all;
  font-size: 16px;
  color: #222;
}
.preview-modal-mask {
  position: fixed;
  z-index: 3000;
  left: 0; top: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.25);
  display: flex;
  align-items: center;
  justify-content: center;
}
.preview-modal {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0,0,0,0.18);
  width: 700px;
  max-width: 96vw;
  padding: 0;
  overflow: hidden;
  animation: fadeIn .2s;
  display: flex;
  flex-direction: column;
  max-height: 90vh;
}
.preview-modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18px 24px 0 24px;
  font-size: 18px;
  font-weight: 600;
}
.preview-modal-close {
  background: none;
  border: none;
  font-size: 28px;
  color: #888;
  cursor: pointer;
  line-height: 1;
}
.preview-modal-body {
  padding: 24px 24px 24px 24px;
  overflow-y: auto;
  max-height: 60vh;
}
</style> 